import {defineStore} from "pinia";
import {deleteSysMenuById, getSysAllMenu, postSysMenu, putSysMenu, putSysMenuStatusById} from "@/api/menu";
import type {TMenuInfo, TMenuParams} from "@/api/menu/type.ts";
import {ElMessage} from "element-plus";

type TState = {
    allMenuList:TMenuInfo[]
}

const useMenuStore = defineStore("Menu",{
    state():TState{
        return {
            allMenuList:[]
        }
    },
    actions:{
        // 添加表单
        async postSysMenuAsync(body:TMenuParams){
            const {message} = await postSysMenu(body);
            ElMessage.success(message);
            await this.getSysAllMenuAsync();
        },
        // 修改表单
        async putSysMenuAsync(body:TMenuParams){
            const {message} = await putSysMenu(body);
            ElMessage.success(message);
            await this.getSysAllMenuAsync();
        },
        // 删除
        async deleteSysMenuByIdAsync(id:string){
            const {message} = await deleteSysMenuById(id);
            ElMessage.success(message);
            await this.getSysAllMenuAsync();
        },
        // 调用获取全部菜单列表的数据
        async getSysAllMenuAsync(){
            const result = await getSysAllMenu();
            this.allMenuList = result.menuList;
        },
        async putSysMenuStatusByIdAsync(id:string,status:number){
            const {message} = await putSysMenuStatusById(id,status);
            ElMessage.success(message);
            await this.getSysAllMenuAsync();
        }
    },
    getters:{
        parentMenuList():TMenu_EL[]{
           return _menuList(this.allMenuList);
        }
    }
});
type TMenu_EL = {
    value:string,
    label:string,
    children:TMenu_EL[]
}
const _menuList = function(menuList:TMenuInfo[]):TMenu_EL[]{
    return menuList.map((item:TMenuInfo)=>{
        let children:TMenu_EL[] = [];
        if(item.children && item.children.length>0){
            children = _menuList(item.children)
        }
        return {
            value:item._id,
            label:item.name,
            children
        }
    })
}
export default useMenuStore;